<template>
  <div class="aftersales-list-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>售后单管理</h3>
          <div class="header-actions">
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              新建售后单
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="售后单号">
            <el-input v-model="searchForm.afterSalesNo" placeholder="请输入售后单号" clearable />
          </el-form-item>
          <el-form-item label="原订单号">
            <el-input v-model="searchForm.orderNo" placeholder="请输入原订单号" clearable />
          </el-form-item>
          <el-form-item label="售后类型">
            <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
              <el-option label="退货退款" value="退货退款" />
              <el-option label="仅退款" value="仅退款" />
              <el-option label="换货" value="换货" />
              <el-option label="维修" value="维修" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="待审核" value="待审核" />
              <el-option label="审核通过" value="审核通过" />
              <el-option label="审核拒绝" value="审核拒绝" />
              <el-option label="待退货" value="待退货" />
              <el-option label="已退货" value="已退货" />
              <el-option label="待退款" value="待退款" />
              <el-option label="已完成" value="已完成" />
              <el-option label="已取消" value="已取消" />
            </el-select>
          </el-form-item>
          <el-form-item label="客户">
            <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable />
          </el-form-item>
          <el-form-item label="申请时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 统计卡片 -->
      <div class="stats-cards">
        <el-row :gutter="16">
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon" style="background: #ecf5ff; color: #409eff;">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ statistics.total }}</div>
                <div class="stat-label">总售后单</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon" style="background: #fdf6ec; color: #e6a23c;">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ statistics.pending }}</div>
                <div class="stat-label">待处理</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon" style="background: #f0f9ff; color: #67c23a;">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ statistics.completed }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon" style="background: #fef0f0; color: #f56c6c;">
                <el-icon><Money /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">¥{{ statistics.refundAmount }}</div>
                <div class="stat-label">退款金额</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 表格区域 -->
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="70" />
        <el-table-column prop="afterSalesNo" label="售后单号" width="150" />
        <el-table-column prop="orderNo" label="原订单号" width="150" />
        <el-table-column prop="type" label="售后类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户" width="120" />
        <el-table-column prop="productName" label="商品" width="200" />
        <el-table-column prop="quantity" label="数量" width="80" />
        <el-table-column prop="refundAmount" label="退款金额" width="120">
          <template #default="{ row }">
            <span v-if="row.refundAmount">¥{{ row.refundAmount.toFixed(2) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="售后原因" width="150" show-overflow-tooltip />
        <el-table-column prop="applyTime" label="申请时间" width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button 
              v-if="row.status === '待审核'" 
              type="success" 
              size="small" 
              @click="handleApprove(row)"
            >
              审核
            </el-button>
            <el-button 
              v-if="row.status === '待退货' || row.status === '已退货'" 
              type="warning" 
              size="small" 
              @click="handleProcess(row)"
            >
              处理
            </el-button>
            <el-button 
              v-if="row.status === '待审核'" 
              type="danger" 
              size="small" 
              @click="handleCancel(row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新建/编辑售后单对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="900px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="原订单号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入原订单号">
                <template #append>
                  <el-button @click="selectOrder">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售后类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择售后类型">
                <el-option label="退货退款" value="退货退款" />
                <el-option label="仅退款" value="仅退款" />
                <el-option label="换货" value="换货" />
                <el-option label="维修" value="维修" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户" prop="customerName">
              <el-input v-model="form.customerName" placeholder="自动获取" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 商品明细 -->
        <el-form-item label="售后商品" prop="items">
          <el-table :data="form.items" border style="width: 100%">
            <el-table-column prop="productName" label="商品名称" width="200" />
            <el-table-column prop="specification" label="规格" width="120" />
            <el-table-column prop="unitPrice" label="单价" width="100">
              <template #default="{ row }">
                ¥{{ row.unitPrice?.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="售后数量" width="150">
              <template #default="{ row }">
                <el-input-number 
                  v-model="row.quantity" 
                  :min="1" 
                  :max="row.maxQuantity"
                  size="small"
                />
              </template>
            </el-table-column>
            <el-table-column label="小计" width="120">
              <template #default="{ row }">
                ¥{{ (row.unitPrice * row.quantity).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="removeItem(scope.$index)"
                  link
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="退款金额" prop="refundAmount">
              <el-input-number 
                v-model="form.refundAmount" 
                :precision="2" 
                :min="0" 
                :step="0.01"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退款方式" prop="refundMethod">
              <el-select v-model="form.refundMethod" placeholder="请选择退款方式">
                <el-option label="原路退回" value="原路退回" />
                <el-option label="银行转账" value="银行转账" />
                <el-option label="现金退款" value="现金退款" />
                <el-option label="余额退款" value="余额退款" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="售后原因" prop="reason">
          <el-select v-model="form.reason" placeholder="请选择售后原因">
            <el-option label="质量问题" value="质量问题" />
            <el-option label="商品破损" value="商品破损" />
            <el-option label="发错货" value="发错货" />
            <el-option label="不想要了" value="不想要了" />
            <el-option label="商品与描述不符" value="商品与描述不符" />
            <el-option label="收到假货" value="收到假货" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <el-form-item label="问题描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="4"
            placeholder="请详细描述售后问题..."
          />
        </el-form-item>

        <el-form-item label="上传凭证">
          <el-upload
            v-model:file-list="form.fileList"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="5"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="el-upload__tip">
            最多上传5张图片，支持jpg、png格式，单张不超过2MB
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          提交
        </el-button>
      </template>
    </el-dialog>

    <!-- 售后单详情对话框 -->
    <el-dialog v-model="detailVisible" title="售后单详情" width="900px">
      <div class="detail-content" v-if="currentRow">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="售后单号">{{ currentRow.afterSalesNo }}</el-descriptions-item>
          <el-descriptions-item label="原订单号">{{ currentRow.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="售后类型">
            <el-tag :type="getTypeTagType(currentRow.type)">{{ currentRow.type }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentRow.status)">{{ currentRow.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户">{{ currentRow.customerName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentRow.phone }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ currentRow.applyTime }}</el-descriptions-item>
          <el-descriptions-item label="退款金额">
            <span v-if="currentRow.refundAmount">¥{{ currentRow.refundAmount.toFixed(2) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="退款方式">{{ currentRow.refundMethod || '-' }}</el-descriptions-item>
          <el-descriptions-item label="售后原因">{{ currentRow.reason }}</el-descriptions-item>
          <el-descriptions-item label="问题描述" :span="2">
            {{ currentRow.description || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">商品明细</el-divider>
        <el-table :data="currentRow.items" border>
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column prop="specification" label="规格" width="120" />
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="{ row }">
              ¥{{ row.unitPrice.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              ¥{{ (row.unitPrice * row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>

        <el-divider content-position="left">处理进度</el-divider>
        <el-timeline>
          <el-timeline-item 
            v-for="(item, index) in currentRow.timeline" 
            :key="index"
            :timestamp="item.time"
            placement="top"
          >
            <el-card>
              <h4>{{ item.title }}</h4>
              <p>{{ item.content }}</p>
              <p class="operator">操作人：{{ item.operator }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog v-model="approveVisible" title="售后审核" width="500px">
      <el-form :model="approveForm" label-width="100px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="approveForm.result">
            <el-radio label="通过">审核通过</el-radio>
            <el-radio label="拒绝">审核拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见">
          <el-input 
            v-model="approveForm.remark" 
            type="textarea" 
            :rows="4"
            placeholder="请输入审核意见..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="approveVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApprove">提交审核</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Search, Refresh, Document, Clock, 
  CircleCheck, Money 
} from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  afterSalesNo: '',
  orderNo: '',
  type: '',
  status: '',
  customerName: '',
  dateRange: []
})

// 统计数据
const statistics = reactive({
  total: 156,
  pending: 23,
  completed: 118,
  refundAmount: 45680.50
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新建售后单')
const formRef = ref(null)
const submitting = ref(false)

// 表单数据
const form = reactive({
  orderNo: '',
  type: '',
  customerName: '',
  phone: '',
  items: [],
  refundAmount: 0,
  refundMethod: '',
  reason: '',
  description: '',
  fileList: []
})

// 表单验证规则
const rules = {
  orderNo: [{ required: true, message: '请输入原订单号', trigger: 'blur' }],
  type: [{ required: true, message: '请选择售后类型', trigger: 'change' }],
  customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  reason: [{ required: true, message: '请选择售后原因', trigger: 'change' }],
  refundAmount: [{ required: true, message: '请输入退款金额', trigger: 'blur' }]
}

// 详情对话框
const detailVisible = ref(false)
const currentRow = ref(null)

// 审核对话框
const approveVisible = ref(false)
const approveForm = reactive({
  result: '通过',
  remark: ''
})

// 获取售后类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    '退货退款': 'danger',
    '仅退款': 'warning',
    '换货': 'primary',
    '维修': 'info'
  }
  return typeMap[type] || ''
}

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    '待审核': 'warning',
    '审核通过': 'success',
    '审核拒绝': 'danger',
    '待退货': 'info',
    '已退货': 'primary',
    '待退款': 'warning',
    '已完成': 'success',
    '已取消': 'info'
  }
  return statusMap[status] || ''
}

// 加载数据
const loadData = () => {
  loading.value = true
  
  // 模拟数据
  setTimeout(() => {
    tableData.value = [
      {
        id: 1,
        afterSalesNo: 'AS202501190001',
        orderNo: 'SO202501150234',
        type: '退货退款',
        customerName: '张三',
        productName: '华为 Mate 60 Pro 12GB+512GB',
        quantity: 1,
        refundAmount: 6999.00,
        status: '待审核',
        reason: '质量问题',
        phone: '13800138000',
        refundMethod: '原路退回',
        description: '手机屏幕有划痕',
        applyTime: '2025-01-19 10:30:00',
        items: [
          {
            productName: '华为 Mate 60 Pro 12GB+512GB',
            specification: '曜金黑',
            quantity: 1,
            unitPrice: 6999.00,
            maxQuantity: 1
          }
        ],
        timeline: [
          {
            title: '提交售后申请',
            content: '客户提交售后申请',
            time: '2025-01-19 10:30:00',
            operator: '张三'
          }
        ]
      },
      {
        id: 2,
        afterSalesNo: 'AS202501190002',
        orderNo: 'SO202501160145',
        type: '换货',
        customerName: '李四',
        productName: '小米14 Ultra 16GB+1TB',
        quantity: 1,
        refundAmount: 0,
        status: '审核通过',
        reason: '商品破损',
        phone: '13900139000',
        description: '包装破损，要求换货',
        applyTime: '2025-01-19 09:15:00',
        items: [
          {
            productName: '小米14 Ultra 16GB+1TB',
            specification: '钛金属',
            quantity: 1,
            unitPrice: 6499.00,
            maxQuantity: 1
          }
        ],
        timeline: [
          {
            title: '提交售后申请',
            content: '客户提交售后申请',
            time: '2025-01-19 09:15:00',
            operator: '李四'
          },
          {
            title: '审核通过',
            content: '售后审核通过，等待客户寄回商品',
            time: '2025-01-19 10:00:00',
            operator: '客服小王'
          }
        ]
      },
      {
        id: 3,
        afterSalesNo: 'AS202501180003',
        orderNo: 'SO202501140089',
        type: '仅退款',
        customerName: '王五',
        productName: 'iPhone 15 Pro Max 256GB',
        quantity: 1,
        refundAmount: 9999.00,
        status: '已完成',
        reason: '不想要了',
        phone: '13700137000',
        refundMethod: '原路退回',
        description: '临时改变主意',
        applyTime: '2025-01-18 14:20:00',
        items: [
          {
            productName: 'iPhone 15 Pro Max 256GB',
            specification: '钛金色',
            quantity: 1,
            unitPrice: 9999.00,
            maxQuantity: 1
          }
        ],
        timeline: [
          {
            title: '提交售后申请',
            content: '客户提交售后申请',
            time: '2025-01-18 14:20:00',
            operator: '王五'
          },
          {
            title: '审核通过',
            content: '售后审核通过',
            time: '2025-01-18 15:00:00',
            operator: '客服小张'
          },
          {
            title: '退款完成',
            content: '退款已原路返回',
            time: '2025-01-18 16:30:00',
            operator: '财务小李'
          }
        ]
      }
    ]
    
    pagination.total = 156
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    afterSalesNo: '',
    orderNo: '',
    type: '',
    status: '',
    customerName: '',
    dateRange: []
  })
  handleSearch()
}

// 分页改变
const handlePageChange = (page) => {
  pagination.page = page
  loadData()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

// 显示新建对话框
const showAddDialog = () => {
  dialogTitle.value = '新建售后单'
  Object.assign(form, {
    orderNo: '',
    type: '',
    customerName: '',
    phone: '',
    items: [],
    refundAmount: 0,
    refundMethod: '',
    reason: '',
    description: '',
    fileList: []
  })
  dialogVisible.value = true
}

// 选择订单
const selectOrder = () => {
  ElMessage.info('订单选择功能开发中...')
}

// 删除商品项
const removeItem = (index) => {
  form.items.splice(index, 1)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      submitting.value = true
      
      setTimeout(() => {
        ElMessage.success('售后单创建成功')
        dialogVisible.value = false
        submitting.value = false
        loadData()
      }, 1000)
    }
  })
}

// 查看详情
const handleView = (row) => {
  currentRow.value = row
  detailVisible.value = true
}

// 审核
const handleApprove = (row) => {
  currentRow.value = row
  approveForm.result = '通过'
  approveForm.remark = ''
  approveVisible.value = true
}

// 提交审核
const submitApprove = () => {
  ElMessage.success('审核提交成功')
  approveVisible.value = false
  loadData()
}

// 处理售后
const handleProcess = (row) => {
  ElMessage.info('售后处理功能开发中...')
}

// 取消售后
const handleCancel = (row) => {
  ElMessageBox.confirm('确定要取消该售后单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('售后单已取消')
    loadData()
  }).catch(() => {})
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.aftersales-list-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-area {
  margin-bottom: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-right: 15px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-content {
  max-height: 600px;
  overflow-y: auto;
}

.operator {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}
</style>

